import { defineStore } from 'pinia'
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import * as postApi from '@/api/post'
import type { Post, Category, Tag, PostData, PostQuery } from '@/api/post'
import {
  favoritePost as apiFavoritePost,
  unfavoritePost as apiUnfavoritePost,
  getPostFavoriteStatus as apiGetPostFavoriteStatus
} from '@/api/post'

export const usePostStore = defineStore('post', () => {
  const posts = ref<Post[]>([])
  const categories = ref<Category[]>([])
  const tags = ref<Tag[]>([])
  const currentPost = ref<Post | null>(null)
  const loading = ref(false)

  // 获取帖子列表
  const fetchPosts = async (query: PostQuery) => {
    try {
      loading.value = true
      const res = await postApi.getPosts(query)
      if (res.code === 200) {
        posts.value = res.data
      }
    } catch (error: any) {
      message.error(error.message || '获取帖子列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取帖子详情
  const fetchPostDetail = async (id: number) => {
    try {
      loading.value = true
      const res = await postApi.getPostById(id)
      if (res.code === 200) {
        currentPost.value = res.data
      }
    } catch (error: any) {
      message.error(error.message || '获取帖子详情失败')
    } finally {
      loading.value = false
    }
  }

  // 创建帖子
  const createPost = async (data: PostData): Promise<boolean> => {
    try {
      loading.value = true
      const res = await postApi.createPost(data)
      if (res.code === 200) {
        message.success('发布成功')
        return true
      }
      return false
    } catch (error: any) {
      message.error(error.message || '发布失败')
      return false
    } finally {
      loading.value = false
    }
  }

  // 更新帖子
  const updatePost = async (id: number, data: Partial<PostData>): Promise<boolean> => {
    try {
      loading.value = true
      const res = await postApi.updatePost(id, data)
      if (res.code === 200) {
        message.success('更新成功')
        return true
      }
      return false
    } catch (error: any) {
      message.error(error.message || '更新失败')
      return false
    } finally {
      loading.value = false
    }
  }

  // 删除帖子
  const deletePost = async (id: number): Promise<boolean> => {
    try {
      loading.value = true
      const res = await postApi.deletePost(id)
      if (res.code === 200) {
        message.success('删除成功')
        posts.value = posts.value.filter(post => post.id !== id)
        return true
      }
      return false
    } catch (error: any) {
      message.error(error.message || '删除失败')
      return false
    } finally {
      loading.value = false
    }
  }

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const res = await postApi.getCategories()
      if (res.code === 200) {
        categories.value = res.data
      }
    } catch (error: any) {
      message.error(error.message || '获取分类列表失败')
    }
  }

  // 获取标签列表
  const fetchTags = async () => {
    try {
      const res = await postApi.getTags()
      if (res.code === 200) {
        tags.value = res.data
      }
    } catch (error: any) {
      message.error(error.message || '获取标签列表失败')
    }
  }

  // 点赞帖子
  const likePost = async (id: number, userId?: number): Promise<boolean> => {
    try {
      const res = await postApi.likePost(id, userId)
      if (res.code === 200) {
        // 更新当前帖子的点赞数
        if (currentPost.value && currentPost.value.id === id) {
          // 根据结果更新点赞数
          currentPost.value.likes = res.data ? 
            currentPost.value.likes + 1 : 
            Math.max(0, currentPost.value.likes - 1);
        }
        // 更新列表中的帖子点赞数
        const post = posts.value.find(p => p.id === id)
        if (post) {
          // 根据结果更新点赞数
          post.likes = res.data ? 
            post.likes + 1 : 
            Math.max(0, post.likes - 1);
        }
        return res.data
      }
      return false
    } catch (error: any) {
      message.error(error.message || '点赞失败')
      return false
    }
  }

  // 收藏帖子
  const favoritePost = async (id: number, userId?: number): Promise<boolean> => {
    try {
      const res = await apiFavoritePost(id, userId)
      if (res.code === 200) {
        return res.data
      }
      return false
    } catch (error: any) {
      message.error(error.message || '收藏失败')
      return false
    }
  }

  // 取消收藏帖子
  const unfavoritePost = async (id: number, userId?: number): Promise<boolean> => {
    try {
      const res = await apiUnfavoritePost(id, userId)
      if (res.code === 200) {
        return res.data
      }
      return false
    } catch (error: any) {
      message.error(error.message || '取消收藏失败')
      return false
    }
  }

  // 获取帖子收藏状态
  const getPostFavoriteStatus = async (id: number, userId?: number): Promise<boolean> => {
    try {
      const res = await apiGetPostFavoriteStatus(id, userId)
      if (res.code === 200) {
        return res.data
      }
      return false
    } catch (error: any) {
      console.error('获取收藏状态失败:', error)
      return false
    }
  }

  return {
    posts,
    categories,
    tags,
    currentPost,
    loading,
    fetchPosts,
    fetchPostDetail,
    createPost,
    updatePost,
    deletePost,
    fetchCategories,
    fetchTags,
    likePost,
    favoritePost,
    unfavoritePost,
    getPostFavoriteStatus
  }
}) 